package com.example.lin.day8_31.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.lin.day8_31.app.MyApplication;
import com.example.lin.day8_31.pojo.Student;

import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private static DBManager instance;
    private final MyDBOpenhelper openhelper;

    public static DBManager getInstance() {
        if (instance == null) {
            synchronized (DBManager.class) {
                if (instance == null) {
                    instance = new DBManager();
                }
            }
        }
        return instance;
    }



    private DBManager() {
        openhelper = new MyDBOpenhelper(MyApplication.getContext());
    }


    public long insert(Student student) {
        SQLiteDatabase db = openhelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put(MyDBOpenhelper.COLUMN_NAME, student.getName());
        values.put(MyDBOpenhelper.COLUMN_AGE, student.getAge());
        values.put(MyDBOpenhelper.COLUMN_SEX, student.getSex());
        long insert = db.insert(MyDBOpenhelper.TABLE_NAME, null, values);
        db.close();
        return insert;
    }

    public int delete(long id) {
        SQLiteDatabase db = openhelper.getReadableDatabase();
        int delete = db.delete(MyDBOpenhelper.TABLE_NAME, MyDBOpenhelper.COLUMN_ID + "=?", new String[]{id + ""});
        db.close();
        return delete;
    }

    public int update(Student student) {
        SQLiteDatabase db = openhelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put(MyDBOpenhelper.COLUMN_NAME, student.getName());
        values.put(MyDBOpenhelper.COLUMN_AGE, student.getAge());
        values.put(MyDBOpenhelper.COLUMN_SEX, student.getSex());
        int update = db.update(MyDBOpenhelper.TABLE_NAME, values, MyDBOpenhelper.COLUMN_ID + "=?", new String[]{student.getId() + ""});
        db.close();
        return update;
    }

    public List<Student> queryAll() {
        SQLiteDatabase db = openhelper.getReadableDatabase();
        String[] columns = {MyDBOpenhelper.COLUMN_ID, MyDBOpenhelper.COLUMN_NAME, MyDBOpenhelper.COLUMN_AGE, MyDBOpenhelper.COLUMN_SEX};
        Cursor cursor = db.query(MyDBOpenhelper.TABLE_NAME, columns, null, null, null, null, null);
        ArrayList<Student> list = null;
        if (cursor.getCount() > 0) {
            list = new ArrayList<>();

            while (cursor.moveToNext()) {
                int id = cursor.getInt(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                String sex = cursor.getString(3);
                list.add(new Student(id, name, sex, age));
            }

        }
        cursor.close();
        db.close();
        return list;
    }
}
